package org.setec.config;

import org.setec.utils.xml.XMLLoader;
import org.setec.config.Configuration;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.util.*;

//@deprecated
public class ConfigurationLoader extends XMLLoader {


    public static InterpretableConfiguration load(String path) {
        try {
            return load(new FileInputStream(new File(path)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static InterpretableConfiguration load(InputStream configInput) {
        InterpretableConfiguration result = new InterpretableConfiguration();

        Document document = null;
        try {
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            document = documentBuilder.parse(configInput);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        result.setMode(getStringAttribute(document, "config|settings|mode", "value" ).toUpperCase());
        result.setStorage(getStringAttribute(document, "config|settings|storage", "path" ));

        List aspectNameList = getStringAttributes(document, "config|aspects|aspect", "class");
        List aspectList = new ArrayList();
        for( Iterator it = aspectNameList.iterator(); it.hasNext(); ){
             String aspectName = (String) it.next();
            Aspect aspect = new Aspect();
            aspect.setClassName(aspectName);

            List aspectJoinPointDefList = getStringAttributes(document, "config|aspects|aspect|joinpoint", "method", "config|aspects|aspect@class=" + aspectName );
            List aspectJoinPointList = new ArrayList();
            for( Iterator jpdit = aspectJoinPointDefList.iterator(); jpdit.hasNext(); ){
                String joinPointDef = (String) jpdit.next();
                String methodName = joinPointDef.split("\\(")[0];
                String argsString = joinPointDef.split("\\(")[1];
                String[] argClasses = argsString.length()==1?new String[0]:argsString.split("\\)")[0].split(",");
                JoinPoint joinPoint = new JoinPoint();
                joinPoint.setMethodName(methodName);
                joinPoint.setArgClassNames(argClasses);
                aspectJoinPointList.add(joinPoint);
            }
            aspect.setJoinPoints(aspectJoinPointList);

            aspectList.add(aspect);
        }
        result.setAspectList(aspectList);

        return result;
    }

}

